//
//  CreateWeightViewController.m
//  WeightMaster
//
//  Created by maoyu on 15/8/20.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "CreateWeightViewController.h"
#import "BDFoundation.h"
#import "WMModels.h"
#import "UIColor+WeightMaster.h"
#import "UIScrollView+TwitterCover.h"
#import <Masonry.h>

@interface CreateWeightViewController () {
    CGFloat _imageAngle;
    OneFingerRotationGestureRecognizer *_gestureRecognizer;
    
    BOOL _isCamera;
    BOOL _isSetCover;
}

@property (nonatomic, strong) NSNumber * unit;
@property (nonatomic) CGFloat weight;

@end

@implementation CreateWeightViewController

- (void)initView {
    WMWeight * weight = [WMDataCache sharedInstance].latestWeight;
    
    self.unit = [WMAppSetting sharedInstance].weightUnit;
    if (WMWeightUnitJin == [self.unit integerValue]) {
        self.unitLabel.text = @"当前体重（斤）";
        self.weight = [weight.value floatValue] * 2;
    }else {
        self.weight = [weight.value floatValue];
    }
    
    self.weightLabel.text = [WMHelper stringValueForWeight:weight.value withUnit:[WMAppSetting sharedInstance].weightUnit];
    
    if (weight.profileImage) {
//        self.profileImageView.image = weight.profileImage;
    }
    
    [self.saveButton setTitleColor:[UIColor mainColor] forState:UIControlStateNormal];
    self.coverButton.hidden = YES;
    
    if (iPhone4) {
        self.rotateViewCenterX.constant = 70;
        self.unitLabelCenterX.constant = - 80;
    }

}

- (void) setupGestureRecognizer
{
    // calculate center and radius of the control
    CGPoint midPoint = CGPointMake(self.wheelImageView.frame.origin.x + self.wheelImageView.frame.size.width / 2,
                                   self.wheelImageView.frame.origin.y + self.wheelImageView.frame.size.height / 2);
    CGFloat outRadius = self.wheelImageView.frame.size.width / 2;
    
    // outRadius / 3 is arbitrary, just choose something >> 0 to avoid strange
    // effects when touching the control near of it's center
    _gestureRecognizer = [[OneFingerRotationGestureRecognizer alloc] initWithMidPoint: midPoint
                                                                         innerRadius: outRadius / 3
                                                                         outerRadius: outRadius
                                                                              target: self];
    [self.wheelImageView addGestureRecognizer: _gestureRecognizer];
}

- (void)back {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelay:0.375];
    [self.navigationController popViewControllerAnimated:NO];
    [UIView commitAnimations];
}

- (void)showSaveView {
    self.saveButton.hidden = NO;
    self.rotatePrompt1Label.hidden = YES;
    self.rotatePrompt2Label.hidden = YES;
}

#pragma 事件函数
- (void)viewDidLoad {
    [super viewDidLoad];
    
     _imageAngle = 0;
    
    [self initView];
    [self setupGestureRecognizer];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)saveWeight:(id)sender {
    WMWeight * wmWeight = [[WMWeight alloc] init];
    wmWeight.value = [NSNumber numberWithFloat:[self.weightLabel.text floatValue]];
    wmWeight.measuringDate = [NSDate date];
    if (YES == _isCamera) {
        [wmWeight  setLocalProfileImage:self.profileImageView.image];
        if (YES == _isSetCover) {
            [[WMAppSetting sharedInstance] setCoverImage:self.profileImageView.image];
        }
    }
    
    [[WMDataCache sharedInstance] addWeight:wmWeight fromCloud:NO];
    
    [self back];
}

- (IBAction)camera:(id)sender {
    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] redButtonIndex:-1 delegate:self];
    [sheet show];
}

- (IBAction)setCover:(id)sender {
    _isSetCover = !_isSetCover;
    if (YES == _isSetCover) {
        [self.coverButton setImage:[UIImage imageNamed:@"cover_on"] forState:UIControlStateNormal];
    }else {
        [self.coverButton setImage:[UIImage imageNamed:@"cover_off"] forState:UIControlStateNormal];
    }
}

#pragma OneFingerRotationGestureRecognizerDelegate
- (void) rotation: (CGFloat) angle {
    [self showSaveView];
    
    // calculate rotation angle
    _imageAngle += angle;
    if (_imageAngle > 360) {
        _imageAngle -= 360;
        _weight ++;
    }else if (_imageAngle < -360) {
        _imageAngle += 360;
        if (_weight > 0) {
            _weight --;
        }
    }
    
    // rotate image and update text field
    self.wheelImageView.transform = CGAffineTransformMakeRotation(_imageAngle *  M_PI / 180);
    CGFloat weight = _weight +_imageAngle/360.0;
    if (weight < 0) {
        weight = 0;
    }
    
    self.weightLabel.text = [NSString stringWithFormat: @"%.1f", weight];
}

#pragma LCActionSheetDelegate
- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) {
        [[CameraManager defaultInstance] showCameraWithViewController:self withEdit:YES];
        [CameraManager defaultInstance].delegate = self;
    }else if (1 == buttonIndex) {
        [[CameraManager defaultInstance] showAlbumWithViewController:self withEdit:YES];
        [CameraManager defaultInstance].delegate = self;
    }
}

#pragma CameraManagerDelegate
- (void)pickerDidCancel {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)pickedImage:(UIImage *)image {
    _isCamera = YES;
    self.profileImageView.image = image;
    [self dismissViewControllerAnimated:YES completion:NULL];
    
    self.cameraButton.hidden = YES;
    self.cameraPromptLabel.hidden = YES;
    self.coverButton.hidden = NO;
    
    [self showSaveView];
}

@end
